package com.xf.zk.curator.example.znode;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.EnsurePath;
import org.apache.zookeeper.CreateMode;

public class EnsureZkPath {
	static String path = "/curator_ensure_path";
	// 创建CuratorFramework 客户端实例，集群服务器地址为127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183，session timeout5000ms
	// 回调策略为ExponentialBackoffRetry，即为retries 3 times with increasing 1000 sleep time between retries
	static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
			.sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

	public static void main(String[] args) throws Exception {
		client.start();

		org.apache.curator.utils.EnsurePath ensurePath = new org.apache.curator.utils.EnsurePath(path);
		// first time syncs and creates if needed
		ensurePath.ensure(client.getZookeeperClient());
		// 直接创建子节点path1，因为前面ensure没有的话，自动创建了path节点
		String path1 = path + "/c1";
		client.create().withMode(CreateMode.EPHEMERAL).forPath(path1, "init".getBytes());
		System.out.println("success create znode: " + path1);
		// subsequent times are NOPs,path已经存在，不做任何操作
		ensurePath.ensure(client.getZookeeperClient());
		// 直接创建子节点path2
		String path2 = path + "/c2";
		client.create().withMode(CreateMode.EPHEMERAL).forPath(path2, "init2".getBytes());
		System.out.println("success create znode: " + path1);
	}
}
